import { TerisRule } from "./TerisRule";
import { MoveDirection, Point } from "./types";
import { SquareGroup } from "./SquareGroup";

function isPoint(obj: any): obj is Point {
  if (typeof obj.x === "undefined") {
    return false;
  }
  return true;
}

/**
 * 方块控制方法类，实现方块的移动旋转
 */
export class TerisControl{
  static move(teris: SquareGroup, targetPoint: Point):boolean;
  static move(teris: SquareGroup, direction: MoveDirection):boolean;
  static move(
    teris: SquareGroup,
    targetPointOrDirection: Point | MoveDirection
  ): boolean {
    if (isPoint(targetPointOrDirection)) {
      if (TerisRule.canIMove(teris.shape, targetPointOrDirection)) {
        teris.centerPoint = targetPointOrDirection;
        return true;
      }
      return false;
    } else {
      const direction = targetPointOrDirection;
      let targetPoint;
      if (direction === MoveDirection.down) {
        targetPoint = {
          x: teris.centerPoint.x,
          y: teris.centerPoint.y + 1,
        };
      } else if (direction === MoveDirection.left) {
        targetPoint = {
          x: teris.centerPoint.x - 1,
          y: teris.centerPoint.y,
        };
      } else {
        targetPoint = {
          x: teris.centerPoint.x + 1,
          y: teris.centerPoint.y,
        };
      }
      return this.move(teris, targetPoint);
    }
  }

  static moveDirectly(teris: SquareGroup, direction: MoveDirection): number{
    let count = 0
    while(this.move(teris,direction)){
      count++
    }
    return count
  }

}